import { isFunction, isObject, isString } from '@/utils/is';

import { i18n } from './setupI18n';
import { formatI18n, formatI18nArr } from './utils';

type I18nGlobalTranslation = {
  (key: string): string;
  (key: string, arg: any): string;
  (key: string, ...arg: any[]): string;
};

function getKey(namespace: string | undefined, key: string) {
  if (!namespace) {
    return key;
  }
  if (key.startsWith(namespace)) {
    return key;
  }
  return `${namespace}.${key}`;
}

export function useI18n(namespace?: string): {
  t: I18nGlobalTranslation;
} {
  const normalFn = {
    t: (key: string) => {
      return getKey(namespace, key);
    },
  };

  if (!i18n) {
    return normalFn;
  }

  const { t, tm } = i18n.global;

  const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => {
    if (!key) return '';
    const path = getKey(namespace, key);
    let temp = tm(path) as string;
    if (isFunction(temp)) {
      return temp(...arg);
    }
    temp = isString(temp) ? temp : path;
    if (!arg) {
      return t(path);
    } else {
      if (arg.length === 1 && isObject(arg[0])) {
        return formatI18n(temp, arg[0]);
      } else {
        return formatI18nArr(temp, ...arg);
      }
    }
  };

  return {
    t: tFn,
  };
}
